<template>
    <!-- 自定义表格 -->
    <div :class="{ bg: tableconfig.hasbg, mytable: true, myicon: tableconfig.hasicon }">
        <!-- 自定义表格上方信息--左右插槽 -->
        <div class="myheader">
            <slot name="mcardleft"></slot>
            <slot name="mcardright"></slot>
        </div>
        <!-- 自定义表格卡片--中间插槽 -->
        <div class="mybody">
            <slot name="mytablebody"></slot>
        </div>
        <!-- 自定义表格-->
        <el-table fit @selection-change="handleSelectChange" @cell-dblclick="doDoubleClick" @cell-mouse-enter="doCellHover"
            @cell-mouse-leave="doCellLeave" @row-click="doRowClick" @sort-change="handlesortChange"
            @select-all="doSelectAll" :cell-style="handleCellStyle" :row-class-name="setIndex"
            v-loading="tableconfig.loading" ref="table" border :data="tableconfig.tabledata" :height="tableconfig.height"
            :max-height="tableconfig.maxheight" v-adaptive="tableconfig.bottomset"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">

            <!-- 表格是否可扩展 -->
            <el-table-column v-if="tableconfig.isExpand" label=" " min-width="40px" style="text-align: center">
                <!-- 有扩展项显示加 -->
                <template slot-scope="scope" v-if="scope.row.children">
                    <span style="margin: 0 auto; display: table; font-weight: bold; cursor: pointer"
                        @click="toggleExpand(scope.row)">-+-</span>
                </template>
                <!-- 无扩展项显示空白 -->
                <template v-else slot-scope="scope">
                    <span style="margin: 0 auto; display: table">{{ scope.row }}</span>
                </template>
            </el-table-column>
            <!-- 表格是否可多选 -->
            <el-table-column v-if="tableconfig.isselection" align="center" :fixed="tableconfig.isfixed">
                <el-table-column type="selection" width="75" :selectable="checkSelectable">
                </el-table-column>
                <template slot="header">
                    <div class="checked-box">
                        <el-checkbox v-model="tableconfig.checkedAll" @change="changeCheckAll">全部</el-checkbox>
                    </div>
                </template>
            </el-table-column>

            <!-- 循环渲染表头 -->
            <template v-for="item in tableconfig.thead">
                <!-- 如果表头属性为function,执行回调 -->
                <el-table-column v-if="item.type == 'function'" :show-overflow-tooltip="true" :sortable="item.sort"
                    :key="item.prop + item.label" :prop="item.prop" align="center" min-width="80px" :label="item.label"
                    :width="item.width || ''" :fixed="item.fixed || false">
                    <template slot-scope="scope">
                        {{ item.callback(scope.row) }}
                    </template>
                </el-table-column>
                <!-- 如果表头属性为slot,执行插槽,插槽名为该列属性 -->
                <el-table-column v-else-if="item.type == 'slot'" :show-overflow-tooltip="false" :sortable="item.sort"
                    :key="item.prop + item.label" :prop="item.prop" min-width="80px" align="center" :label="item.label"
                    :width="item.width || ''" :fixed="item.fixed || false">
                    <template slot-scope="scope">
                        <slot :data="scope.row" :name="item.prop"></slot>
                    </template>
                </el-table-column>
                <!-- 其他情况默认渲染 -->

                <el-table-column v-else :show-overflow-tooltip="true" :key="item.prop + item.label" :sortable="item.sort"
                    :prop="item.prop" align="left" :label="item.label" min-width="80px" :width="item.width || ''"
                    :fixed="item.fixed || false"> </el-table-column>
            </template>
            <template slot="empty">
                <img class="nullDataImg" src="@/assets/images/noneData.svg" alt="" />
            </template>
        </el-table>
        <!-- 分页部分 -->
        <div>
            <p class="error"><span v-if="tableconfig.isError">*当前上传的库存信息，匹配标准库后，存在重复型号，将重复型号删除</span></p>
            <el-pagination :disabled="tableconfig.loading" v-if="tableconfig.ispagination"
                :current-page="tableconfig.currentpage" :page-sizes="tableconfig.pagesizes"
                :page-size="tableconfig.pagesize" :total="tableconfig.total" background
                :class="{ 'system-pagination': hasclasssystempagination, normal: !hasclasssystempagination }"
                layout="total,sizes,prev, pager, next,jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
</template>
  
<script>
import { off } from 'process';
import { log } from 'util';

export default {
    name: 'my-table',
    data() {
        return {
            // 表格配置
            tableconfig: {
                loading: false,
                // top部分背景色
                hasbg: true,
                //top部分是否蓝色竖条
                hasicon: false,
                // 是否表格行可展开
                isExpand: false,
                // 是否还有可选择列
                isselection: true,
                // 首列index
                isindex: false,
                isfixed: false,
                id: '',
                // 默认高度
                size: '',
                maxheight: undefined,
                height: '100px',
                // checkedAll: false, //全选所有
                // 表头
                thead: [],
                // 表格渲染数据
                tabledata: [],
                // 是否显示分页
                ispagination: false,
                // 当前页
                currentpage: 1,
                // 每页显示数据条数数
                pagesizes: [10, 20, 50, 100],
                //每页显示数据条数
                pagesize: 10,
                isError: false,
                // 数据总条数
                total: 0,
                rect: '',
                bottomset: { bottomOffset: 20 },
            },
            status: false,
            section: [],
        };
    },
    props: {
        config: {
            type: Object,
            default: () => { },
        },
        checkedStatus: {
            type: Boolean,
            default: false,
        }
    },
    created() {

    },
    mounted() {
        // 获取table高度;
        this.handleHeightChange();
        this.initconfig();
        // 执行该方法表格回到顶端
        this.$on('handleGoTop', () => {
            setTimeout(() => {
                this.$refs.table.bodyWrapper.scrollTop = 0;
            }, 200);
        });
    },
    methods: {
        //绑定row-key 防止唯一性
        initconfig() {
            for (let key in this.config) {
                if (Object.keys(this.tableconfig).includes(key)) {
                    this.tableconfig[key] = this.config[key];
                }
            }
            // this.tableconfig.thead = this.tableconfig.thead.filter((x) => {
            //   return !x.hide;
            // });
        },
        // 高度变化执行
        handleHeightChange() {
            console.log('this.$refs.table',  this.$refs.table)
            setTimeout(() => {
                const height =
                    window.innerHeight - this.$refs.table.$el.getBoundingClientRect().top -
                    this.tableconfig.bottomset.bottomOffset;
                this.$refs.table.layout.setHeight(height);
                this.$refs.table.doLayout();
            }, 550);
            // if (!this.config.maxheight) {
            //   if (document.body.clientHeight - this.$refs.table.$el.getBoundingClientRect().bottom - 80 < 0) {
            //     this.tableconfig.maxheight = '300px';
            //   }
            //
            //     this.tableconfig.maxheight = document.body.clientHeight - this.$refs.table.$el.getBoundingClientRect().top - 70 + 'px';
            //
            // }
        },
        checkSelectable(row) {
            if (this.status) {
                return false;
            } else {
                return true;
            }
        },
        // 为每条数据添加 key =index
        setIndex({ row, rowIndex }) {
            row.index = rowIndex;
        },
        // 选择需要的/取消选中
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.table.toggleRowSelection(row);
                });
            } else {
                this.$refs.table.clearSelection();
            }
        },
        //改变全选所有复选框
        changeCheckAll(val) {
            console.log(val, 'valllllllllllll');
            if (val) {
                console.log(val, 'val444444444444444');
                this.$emit('checkedAll', this.tableconfig.checkedAll);
                console.log(val, 'val');
                // 全选选中时当前页所有数据选中
                this.tableconfig.tabledata.forEach(row => {
                    if (row) {
                        this.$refs.table.toggleRowSelection(row, true);
                    }
                });
            } else {

                this.$emit('checkedAll', this.tableconfig.checkedAll);
                this.$refs.table.clearSelection();
            }
        },
        // 扩展
        toggleExpand(row) {
            let $table = this.$refs.table;
            $table.toggleRowExpansion(row);
        },
        handleSizeChange(val) {
            if (this.$parent.handleSizeChange) {
                this.$parent.handleSizeChange(val);
            }
            this.$refs.table.bodyWrapper.scrollTop = 0;
        },
        handleCurrentChange(val) {
            if (this.$parent.handleCurrentChange) {
                this.$parent.handleCurrentChange(val);
            }
            this.$refs.table.bodyWrapper.scrollTop = 0;
        },
        // 选中选项发生变化时执行
        handleSelectChange(section) {
            this.$nextTick(() => {
                console.log(this.status, 'this.statusthis.status');
                if (this.status) {
                    section = this.tableconfig.tabledata;
                    this.tableconfig.checkedAll = true;
                    if (this.$parent.handleSelectChange) {
                        console.log(section, 'sectionsectionsectionsection');
                        this.$parent.handleSelectChange(section);
                    }
                    this.tableconfig.tabledata.forEach(row => {
                        if (row) {
                            this.$refs.table.toggleRowSelection(row, true);
                        }
                    });
                } else {

                    if (this.$parent.handleSelectChange) {
                        this.$parent.handleSelectChange(section);
                    }
                }
            })
        },
        doDoubleClick() {
            if (this.$parent.doDoubleClick) {
                this.$parent.doDoubleClick();
            }
        },
        doRowClick(row) {
            if (this.$parent.doRowClick) {
                this.$parent.doRowClick(row);
            }
        },
        doSelectAll() {
            if (this.$parent.doRowClick) {
                this.$parent.doSelectAll();
            }
        },
        doCellHover(row, column, cell, event) {
            if (this.$parent.doCellHover) {
                this.$parent.doCellHover(row, column, cell, event);
            }
        },
        doCellLeave(row, column, cell, event) {
            if (this.$parent.doCellLeave) {
                this.$parent.doCellLeave(row, column, cell, event);
            }
        },
        handlesortChange(column, prop, order) {
            if (this.$parent.handlesortChange) {
                this.$parent.handlesortChange(column, prop, order);
            }
        },
        //首列indexd递增
        indexMethod(index) {
            return (this.tableconfig.currentpage - 1) * this.tableconfig.pagesize + index + 1;
        },
        // cell 样式  数量和价格右对齐
        handleCellStyle(x) {
            if (x.column.property && x.column.property.toLowerCase().includes('price')) {
                return { 'text-align': 'right' };
            }
            // if (x.column.property && x.column.property.toLowerCase().includes('quantity')) {
            //     return { 'text-align': 'right' };
            // }
        },
    },
    computed: {
        hasclasssystempagination() {
            return !!this.tableconfig.bottomset.bottomOffset;
        },
    },
    watch: {
        config: {
            handler() {
                this.initconfig();
            },
            immediate: true,
            deep: true,
        },
        checkedStatus: {
            handler(val, old) {
                this.status = val;
                this.tableconfig.checkedAll = val;
                this.changeCheckAll(val)
                console.log(this.status, this.tableconfig.checkedAll, 'watch33333333333322');
            },
            // immediate: true,
            deep: true,
        }
    },
};
</script>
  
<style lang="scss" scoped>
.mytable {
    ::v-deep .el-table__empty-block {
        height: 180px !important;
    }

    ::v-deep .el-table__body-wrapper {
        min-height: 240px !important;
    }

    ::v-deep .el-select {
        width: 100%;
    }

    .myheader {
        padding: 5px 10px;
        display: flex;
        justify-content: space-between;
    }

    .myheader:empty {
        display: none;
    }

    ::v-deep .el-table__header .el-table-column--selection .cell .el-checkbox:after {
        content: "本页";
        color: #606266;
        font-weight: 500;
        margin-left: 10px;
        font-size: 14px;
    }

    .checked-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;

        ::v-deep .el-checkbox:last-of-type {
            margin-right: auto !important;
        }

    }

    .mybody {
        padding: 10px 10px;
    }

    .mybody:empty {
        display: none;
    }

    .bg {
        background: #f4f6fb;
    }

    .myicon {
        position: relative;
        margin-left: 20px;
    }
    .nullDataImg{
        margin-top: 50%;
    }
    .myicon::before {
        content: ' ';
        display: inline-block;
        background: #1890ff;
        width: 5px;
        height: 21px;
        position: absolute;
        left: -20px;
        margin: 0px 5px;
    }

    .el-table {

        //   margin-bottom: 50px;
        .el-table__body {
            height: 100%;
        }

        ::v-deep .el-table__expand-icon {
            display: none;
        }
    }

    ::v-deep.el-table tbody .cell {
        height: 32px !important;
        line-height: 32px !important;
        .el-button--primary{
            height: 27px !important;
        }
    }

    .system-pagination {
        position: fixed;
        bottom: 20px;
        background: #fff;
        right: 20px;
        text-align: right;
    }

    .normal {
        padding: 5px 10px;
        background: #fff;
        text-align: right !important;
    }

    @keyframes mymove {
        100% {
            opacity: 1;
            transform: translateY(0%);
        }

        60% {
            opacity: 0.4;
        }

        30% {
            opacity: 0.2;
        }

        0% {
            opacity: 0.1;
            transform: translateY(-50%);
        }
    }

    .error {
        font-size: 14px;
        font-weight: 400;
        height: 20px;
        color: #E02020;
        line-height: 20px;
    }
}
</style>
  